import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { Icon as AIcon, Tooltip } from 'antd';
import Map from 'ol/Map';
import Overlay from 'ol/Overlay';
import View from 'ol/View';
import TileLayer from 'ol/layer/Tile';
import { DragBox, Select } from 'ol/interaction';
import { platformModifierKeyOnly } from 'ol/events/condition';
import XYZ from 'ol/source/XYZ';
// 图层
import { Vector } from 'ol/layer';
// 数据源
import { Vector as VectorSource } from 'ol/source';
// 要素
import Feature from 'ol/Feature';
// 样式
import { Icon, Style, Text, Fill, Stroke } from 'ol/style';
import LineString from 'ol/geom/LineString';
import Point from 'ol/geom/Point';
import mockData from './mock';
import mockData2 from './mock2';
import mockData3 from './mock3';
// 坐标系转化
import { fromLonLat, toLonLat } from 'ol/proj';
import './openlayers.less';

import jinggai from './../../images/jinggai.png';
import jianyafa from './../../images/jianyafa.png';
import yaogan from './../../images/yaogan.jpg';
import jiedao from './../../images/jiedao.jpg';

@connect(({ devices, loading }) => ({
  devices,
}))
class BasicList extends PureComponent {
  constructor(props) {
    super(props);
    this.scrollInterval = '';
    this.map = null;
    this.state = {
      points: [[89.177699, 42.95369],
        [89.189115, 42.943051],
        [89.185166, 42.942251],
        [89.185166, 42.943251],
        [89.173708, 42.945651],
        [89.168429, 42.941251],
        [89.169429, 42.940251],
        [89.168429, 42.944251],
        [89.178386, 42.943051],
        [89.178214, 42.941651],
        [89.186282, 42.943451],
      ],
      markerArr: [],
      mapType: 'road',
      showMapType: true,
      layers: [
        new TileLayer({
          title: '天地图卫星影像',
          visible: false,
          source: new XYZ({
            url: 'http://t3.tianditu.com/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=49ea1deec0ffd88ef13a3f69987e9a63',
          }),
        }),
        new TileLayer({
          title: '天地图路网',
          visible: true,
          source: new XYZ({
            url: 'http://t4.tianditu.com/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=49ea1deec0ffd88ef13a3f69987e9a63',
          }),
        }),
        new TileLayer({
          title: '天地图文字标注',
          source: new XYZ({
            url: 'http://t3.tianditu.com/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk=49ea1deec0ffd88ef13a3f69987e9a63',
          }),
        }),

      ],
    };
  }

  changeMapType = (maptype) => {
    if (maptype === this.state.mapType) {
      return false;
    }
    if (maptype === 'sensing') {
      this.state.layers[0].setVisible(true);
      this.state.layers[1].setVisible(false);
    } else if (maptype === 'road') {
      this.state.layers[1].setVisible(true);
      this.state.layers[0].setVisible(false);
    }
    this.setState({
      mapType: maptype,
    });

  };

  componentDidMount() {
    //http://222.240.193.158:16666/geoserver/tulufan/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=tulufan:manholecover&outputFormat=application%2Fjson
    //http://t2.tianditu.com/DataServer?T=vec_w&X=12253&Y=6021&L=14&tk=174705aebfe31b79b3587279e211cb9a
    let map = this.map = new Map({
      target: 'mapDiv',
      layers: this.state.layers,
      view: new View({
        center: fromLonLat([89.16108996813949, 42.97498769970309]),//经纬度
        zoom: 13,
        maxZoom: 18,
        minZoom: 5,
      }),
    });

    //绘制点
    let markFeature = [];

    for (let i = 0; i < this.state.points.length; i++) {
      let point = this.setPoint(this.state.points[i], '供水阀' + i);
      markFeature.push(point);
    }
    console.log('markFeature', markFeature);
    // 创建标注的数据源
    var vectorSource = new VectorSource({
      features: markFeature,
    });
    // 创建标注图层
    var vectorLayer = new Vector({
      source: vectorSource,
    });
    // 将标注图层添加到地图上
    // map.addLayer(vectorLayer);


    // a normal select interaction to handle click
    let select = new Select();
    map.addInteraction(select);

    let selectedFeatures = select.getFeatures();

// a DragBox interaction used to select features by drawing boxes
    let dragBox = new DragBox({
      condition: platformModifierKeyOnly,
    });

    map.addInteraction(dragBox);

    dragBox.on('boxend', function() {
      // features that intersect the box geometry are added to the
      // collection of selected features

      // if the view is not obliquely rotated the box geometry and
      // its extent are equalivalent so intersecting features can
      // be added directly to the collection
      var rotation = map.getView().getRotation();
      console.log('rotation', rotation);
      var oblique = rotation % (Math.PI / 2) !== 0;
      var candidateFeatures = oblique ? [] : selectedFeatures;
      var extent = dragBox.getGeometry().getExtent();
      console.log('oblique', oblique);
      console.log('extent', extent);
      console.log('vectorSource',vectorSource)
      vectorSource.forEachFeatureIntersectingExtent(extent, function(feature) {
        candidateFeatures.push(feature);
      });

      mockvectorSource.forEachFeatureIntersectingExtent(extent, function(feature) {
        candidateFeatures.push(feature);
      });


      // when the view is obliquely rotated the box extent will
      // exceed its geometry so both the box and the candidate
      // feature geometries are rotated around a common anchor
      // to confirm that, with the box geometry aligned with its
      // extent, the geometries intersect
      if (oblique) {
        var anchor = [0, 0];
        var geometry = dragBox.getGeometry().clone();
        geometry.rotate(-rotation, anchor);
        var extent$1 = geometry.getExtent();
        candidateFeatures.forEach(function(feature) {
          var geometry = feature.getGeometry().clone();
          geometry.rotate(-rotation, anchor);
          if (geometry.intersectsExtent(extent$1)) {
            selectedFeatures.push(feature);
          }
        });
      }

    });

// clear selection when drawing a new box and when clicking on the map
    dragBox.on('boxstart', function() {
      console.log('boxstart');
      selectedFeatures.clear();
    });

    var infoBox = document.getElementById('info');

    // selectedFeatures.on(['add', 'remove'], function() {
    //   var names = selectedFeatures.getArray().map(function(feature) {
    //     return feature.get('name');
    //   });
    //   if (names.length > 0) {
    //     infoBox.innerHTML = names.join(', ');
    //   } else {
    //     infoBox.innerHTML = 'No countries selected';
    //   }
    // });

    const that = this;
    //绘制弹出框
    var container = document.getElementById('popup');
    var header = document.getElementById('popup-header');
    var content = document.getElementById('popup-content');
    var popupCloser = document.getElementById('popup-closer');
    var popup = new Overlay({
      //设置弹出框的容器
      element: container,
      //是否自动平移，即假如标记在屏幕边缘，弹出时自动平移地图使弹出框完全可见
      autoPan: true,
    });
    popupCloser.addEventListener('click', function() {
      popup.setPosition(undefined);
    });
    map.on('click', function(e) {
      //在点击时获取像素区域;
      console.log(toLonLat(e.coordinate))


      var feature = map.forEachFeatureAtPixel(e.pixel, function(feature, layer) {
        return feature;
      });

      if (feature) {
        console.log('feature', feature);

        var coordinates = feature.getGeometry().getCoordinates();

        let iconName = feature.get('name');
        //设置弹出框内容，可以HTML自定义
        header.innerHTML = '<span>' + iconName + '</span>';
        content.innerHTML = '<p>展示该点相关属性</p>';
        //设置popup 的显示位置
        if (feature.getGeometry().getType() === 'Point') {
          popup.setPosition(coordinates);
          if (iconName.indexOf('manholecover') >= 0) {
            //   feature.setStyle( new Style({
            //     /**{olx.style.IconOptions}类型*/
            //     image: new Icon({
            //       anchor:[0.5,1],
            //       src: jinggai2,
            //     }),
            //   }))
          }

        } else if (feature.getGeometry().getType() === 'LineString') {
          coordinates = e.coordinate;
          popup.setPosition(coordinates);
          selectedFeatures.push(feature);
          // feature.setStyle(new Style({
          //   stroke: new Stroke({
          //     width: 3,
          //     color: [255, 0, 234, 1],
          //   }),
          // }));
        }
        //显示popup
        map.addOverlay(popup);


      } else {
        popup.setPosition(undefined);
      }
    });

    map.on('moveend', function(e) {
      var zoom = map.getView().getZoom();  //获取当前地图的缩放级别
      console.log(zoom);
      var center = map.getView().getCenter();
      console.log(toLonLat(center));
    });


    for (let i = 0; i < mockData3.features.length; i++) {
      let lineFeature = [];
      for (let j = 0; j < mockData3.features[i].geometry.coordinates[0].length; j++) {
        lineFeature.push(fromLonLat(mockData3.features[i].geometry.coordinates[0][j]));
      }
      //绘制线----------------------------------------------
      let feature = new Feature({
        geometry: new LineString(lineFeature),
        name: mockData3.features[i].properties.feature,
      });

      feature.setStyle(new Style({
        stroke: new Stroke({
          width: 3,
          color: [0, 163, 251, 1],
        }),
      }));

      let source = new VectorSource({
        features: [feature],
      });

      let layer = new Vector({
        source: source,
      });
      map.addLayer(layer);
    }

    //绘制模拟数据
    let mockmarkFeature = [];
    for (let i = 0; i < mockData.features.length; i++) {
      let point = this.setPoint(mockData.features[i].geometry.coordinates, mockData.features[i].id, jinggai);
      mockmarkFeature.push(point);
    }
    // 创建标注的数据源
    let mockvectorSource = new VectorSource({
      features: mockmarkFeature,
    });
    // 创建标注图层
    let mockvectorLayer = new Vector({
      source: mockvectorSource,
    });
    // 将标注图层添加到地图上
    map.addLayer(mockvectorLayer);

    //绘制模拟数据
    let mockmarkFeature2 = [];
    for (let i = 0; i < mockData2.features.length; i++) {
      let point = this.setPoint(mockData2.features[i].geometry.coordinates, mockData2.features[i].id, jianyafa);
      mockmarkFeature2.push(point);
    }
    // 创建标注的数据源
    let mockvectorSource2 = new VectorSource({
      features: mockmarkFeature2,
    });
    // 创建标注图层
    let mockvectorLayer2 = new Vector({
      source: mockvectorSource2,
    });
    // 将标注图层添加到地图上
    map.addLayer(mockvectorLayer2);


  }

  setCenter = () => {
    let view = this.map.getView();
    view.setZoom(13);
    let wh = fromLonLat([89.16108996813949, 42.97498769970309]);
    view.setCenter(wh);

  };
  ZoonIn = () => {
    let view = this.map.getView();
    let zoom = view.getZoom();
    view.setZoom(zoom + 1);
  };
  ZoonOut = () => {
    let view = this.map.getView();
    let zoom = view.getZoom();
    view.setZoom(zoom - 1);
  };
  setPoint = (coord, name, img) => {
    let point = new Feature({
      geometry: new Point(fromLonLat(coord)),
      name: name,
    });
    //设置图标的样式
    point.setStyle(this.setMakerStyle(point, img));
    return point;
  };
  setMakerStyle = (feature, img) => {
    return new Style({
      /**{olx.style.IconOptions}类型*/
      image: new Icon({
        anchorOrigin: 'top-right',
        offsetOrigin: 'top-right',
        //图标缩放比例
        scale: 1,
        //透明度
        opacity: 1,
        //图标的url
        src: img ? img : 'http://111.75.54.230:8086/upload/5/5c/5c75e76cebd9df08d84803a9.png',
      }),
      text: new Text({
        //位置
        textAlign: 'center',
        //基准线
        textBaseline: 'middle',
        //文字样式
        font: 'normal 14px 微软雅黑',
        //文本内容
        // text: feature.get('name'),
        //文本填充样式（即文字颜色）
        fill: new Fill({ color: '#fe1b2e' }),
        stroke: new Stroke({ color: '#ffcc33', width: 2 }),
      }),
    });
  };

  render() {
    return <div style={{
      height: '100%',
      width: '100%',
      overflow: 'hidden',
      position: 'relative',
    }}>
      <div id={'mapDiv'} style={{
        display: 'flex',
        height: '100%',
        flexDirection: 'column',
        justifyContent: 'center',
        alignItems: 'center',
      }}>
      </div>
      <div id="popup" className="ol-popup">
        <a href="#" id="popup-closer" className="ol-popup-closer"></a>
        <div id="popup-header" className={'ol-popup-header'}></div>
        <div id="popup-content" className={'ol-popup-content'}></div>
      </div>
      <div id="info"></div>
      <div className={`maptype ${this.state.showMapType ? 'maptype_active' : ''}`}>
        <h3>图层控制</h3>
        <div className="maptype_item">
          <img src={yaogan} alt=""/>
          <span className={this.state.mapType === 'sensing' ? 'active' : ''} onClick={() => {
            this.changeMapType('sensing');
          }}>遥感图</span>
        </div>
        <div className="maptype_item">
          <img src={jiedao} alt=""/>
          <span className={this.state.mapType === 'road' ? 'active' : ''} onClick={() => {
            this.changeMapType('road');
          }}>街道图</span>
        </div>
      </div>
      <div className="map_control">
        <div className="map_control_item" onClick={this.setCenter}>
          <Tooltip title={'全图'}>
            <AIcon type="border-outer"/>
          </Tooltip>
        </div>
        <div className="map_control_item" onClick={this.ZoonIn}>
          <Tooltip title={'放大'}>
            <AIcon type="plus-circle"/>
          </Tooltip>
        </div>
        <div className="map_control_item" onClick={this.ZoonOut}>
          <Tooltip title={'缩小'}>
            <AIcon type="minus-circle"/>
          </Tooltip>
        </div>
        <div className="map_control_item">
          <Tooltip title={'框选'}>
            <AIcon type="select"/>
          </Tooltip>
        </div>
        <div className="map_control_item" onClick={() => {
          this.setState({
            showMapType: !this.state.showMapType,
          });
        }}>
          <Tooltip title={'切换图层'}>
            <AIcon type="snippets"/>
          </Tooltip>
        </div>
      </div>
    </div>;
  }
}

export default BasicList;
